package io.renren.modules.sys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.toolkit.StringUtils;

import io.renren.common.annotation.SysLog;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.frt.entity.DistrictEntity;
import io.renren.modules.frt.entity.TaskEntity;
import io.renren.modules.frt.entity.TaskUserEntity;
import io.renren.modules.frt.service.DistrictService;
import io.renren.modules.frt.service.TaskService;
import io.renren.modules.frt.service.TaskUserService;
import io.renren.modules.sys.constant.DictConst;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.form.PasswordForm;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;

/**
 * 系统用户
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年10月31日 上午10:40:10
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private DistrictService districtService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private TaskUserService taskUserService;

	/**
	 * 所有用户列表，查看分级/审核用户
	 */
	@SuppressWarnings("unchecked")
	@GetMapping("/list")
	@RequiresPermissions("sys:user:list")
	public R list(@RequestParam Map<String, Object> params) {
		
		params.put("userId", this.getUserId());
		PageUtils page = sysUserService.queryPage(params);

		List<SysUserEntity> list = (List<SysUserEntity>) page.getList();
		if (list != null && list.size() > 0) {
			for (SysUserEntity user : list) {
				if (StringUtils.isNotEmpty(user.getProvince())) {
					DistrictEntity province = districtService.selectOne(new EntityWrapper<DistrictEntity>().eq("code", user.getProvince()));
					user.setProvinceName(province != null ? province.getName() : "");
				}
				if (StringUtils.isNotEmpty(user.getCity())) {
					DistrictEntity city = districtService.selectOne(new EntityWrapper<DistrictEntity>().eq("code", user.getCity()));
					user.setCityName(city != null ? city.getName() : "");
				}
				if (StringUtils.isNotEmpty(user.getCountry())) {
					DistrictEntity country = districtService.selectOne(new EntityWrapper<DistrictEntity>().eq("code", user.getCountry()));
					user.setCountryName(country != null ? country.getName() : "");
				}
			}
		}
		return R.ok().put("page", page);
	}

	/**
	 * 获取登录的用户信息
	 */
	@GetMapping("/info")
	public R info() {
		return R.ok().put("user", getUser());
	}

	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@PostMapping("/password")
	public R password(@RequestBody PasswordForm form) {
		Assert.isBlank(form.getNewPassword(), "新密码不为能空");

		// sha256加密
		String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex();
		// sha256加密
		String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex();

		// 更新密码
		boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
		if (!flag) {
			return R.error("原密码不正确");
		}

		return R.ok();
	}

	/**
	 * 用户信息
	 */
	@GetMapping("/info/{userId}")
	@RequiresPermissions("sys:user:info")
	public R info(@PathVariable("userId") Long userId) {
		SysUserEntity user = sysUserService.selectById(userId);

		// 获取用户所属的角色列表
		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
		user.setRoleIdList(roleIdList);

		return R.ok().put("user", user);
	}

	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@PostMapping("/save")
	@RequiresPermissions("sys:user:save")
	public R save(@RequestBody SysUserEntity user) {
		ValidatorUtils.validateEntity(user, AddGroup.class);

		List<Long> roleIdList = new ArrayList<>();
		if (DictConst.USER_LEVEL.ADMIN.getKey() == user.getLevel()) {// 管理员新增省级用户，需要判断省级用户唯一
			SysUserEntity dbUser = sysUserService
					.selectOne(new EntityWrapper<SysUserEntity>().eq("province", user.getProvince()).eq("level", user.getLevel() + 1));
			if (dbUser != null) {
				return R.error("该省级用户已存在");
			}
			roleIdList.add(DictConst.DEFAULT_ROLE_ID.PROVINCE.getKey());
		} else if (DictConst.USER_LEVEL.PROVINCE.getKey() == user.getLevel()) {// 市级唯一
			SysUserEntity dbUser = sysUserService
					.selectOne(new EntityWrapper<SysUserEntity>().eq("city", user.getCity()).eq("level", user.getLevel() + 1));
			if (dbUser != null) {
				return R.error("该市级用户已存在");
			}
			roleIdList.add(DictConst.DEFAULT_ROLE_ID.CITY.getKey());
		} else if (DictConst.USER_LEVEL.CITY.getKey() == user.getLevel()) {// 县级唯一
			SysUserEntity dbUser = sysUserService
					.selectOne(new EntityWrapper<SysUserEntity>().eq("country", user.getCountry()).eq("level", user.getLevel() + 1));
			if (dbUser != null) {
				return R.error("该县级用户已存在");
			}
			roleIdList.add(DictConst.DEFAULT_ROLE_ID.COUNTRY.getKey());
		}else if (DictConst.USER_LEVEL.COUNTRY.getKey() == user.getLevel()) {// 县级用户新增填报人
			roleIdList.add(DictConst.DEFAULT_ROLE_ID.NONE.getKey());
		}
		user.setRoleIdList(roleIdList);
		
		SysUserEntity shiroUser = getUser();
		user.setCreateUserId(shiroUser.getUserId());
		user.setParentId(shiroUser.getUserId());
		user.setLevel(shiroUser.getLevel() + 1);// 只能由上级新增下级
		
		user.setStatus(1);//默认正常
		user.setCheckStatus(0);//默认未审核
		user.setTenantId(1l);//默认为1
		
		sysUserService.save(user);

		return R.ok();
	}

	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@PostMapping("/update")
	@RequiresPermissions("sys:user:update")
	@Transactional
	public R update(@RequestBody SysUserEntity user) {
		ValidatorUtils.validateEntity(user, UpdateGroup.class);

		SysUserEntity dbUser = sysUserService.selectById(user.getUserId());
		user.setLevel(dbUser.getLevel());// 级别不能改
		
		sysUserService.update(user);
		if("check".equals(user.getFlag())) {
			if(user.getCheckStatus() == 1 && user.getLevel() != io.renren.modules.sys.constant.DictConst.USER_LEVEL.NONE.getKey()) {//审核通过，分配管理员已下发的任务，填报人除外，那个需要指派
				List<TaskEntity> taskList = taskService.selectList(new EntityWrapper<TaskEntity>().eq("send_status", io.renren.modules.frt.constant.DictConst.SEND_STATUS.SENDED.getKey()));
				List<TaskUserEntity> taskUserList = new ArrayList<>();
				for(TaskEntity task : taskList) {
					TaskUserEntity taskUser = new TaskUserEntity();
					taskUser.setTaskId(task.getId());
					taskUser.setUserId(user.getUserId());
					if(io.renren.modules.sys.constant.DictConst.USER_LEVEL.COUNTRY.getKey() == user.getLevel()) {//下发到县级用户，默认为未指派
						taskUser.setPointStatus(io.renren.modules.frt.constant.DictConst.POINT_STATUS.UNPOINT.getKey());
					}
					taskUser.setReportStatus(io.renren.modules.frt.constant.DictConst.REPORT_STATUS.UNREPORT.getKey());
					
					taskUserList.add(taskUser);
				}
				if(taskUserList.size() > 0) {
					taskUserService.insertBatch(taskUserList);
				}
			}
		}

		return R.ok();
	}

	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@PostMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public R delete(@RequestBody Long[] userIds) {
		if (ArrayUtils.contains(userIds, 1L)) {
			return R.error("系统管理员不能删除");
		}

		if (ArrayUtils.contains(userIds, getUserId())) {
			return R.error("当前用户不能删除");
		}

		sysUserService.deleteBatch(userIds);

		return R.ok();
	}

	/**
	 * 填报人列表
	 */
	@GetMapping("/select")
	@RequiresPermissions("sys:user:select")
	public R select(@RequestParam("level")Long level, @RequestParam("country")String country, @RequestParam("flag")String flag) {
		Map<String, Object> map = new HashMap<>();
		map.put("level", level);
		if(StringUtils.isNotEmpty(country)) {
			map.put("country", country);
		}
		if("point".equals(flag)) {//指派的填报人是已审核的
			map.put("check_status", 1);
		}
		List<SysUserEntity> list = sysUserService.selectByMap(map);

		return R.ok().put("list", list);
	}
}
